package fr.gdi.android.news.api;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;

import com.android.vending.licensing.AESObfuscator;
import com.android.vending.licensing.LicenseChecker;
import com.android.vending.licensing.LicenseCheckerCallback;
import com.android.vending.licensing.ServerManagedPolicy;

public abstract class AbstractLicensingActivity extends Activity implements LicenseCheckerCallback
{
    private static final int LICENSE_DIALOG = 1001; 

    
    private boolean licensed = true;
    private boolean didCheck = false;
    private boolean checkingLicense = false;
    private ApplicationErrorCode errorCode;

    protected ProgressDialog progressDialog;
    
    
    private LicenseChecker mChecker;
    private Handler mHandler;
    
    protected byte[] getSalt()
    {
        return null;
    }
    
    protected String getPublicKey()
    {
        return null;
    }
    
    @Override
    public void allow()
    {
        if (isFinishing()) return;

        
        licensed = true;
        checkingLicense = false;
        didCheck = true;
        
        mHandler.post(new Runnable() {
            public void run() 
            {
                doProcess();
            }
        });
    }
    
    private void doProcess()
    {
        progressDialog.dismiss();
        process();
    }
    
    @Override
    public void dontAllow()
    {
        if (isFinishing()) return;

        licensed = false;
        checkingLicense = false;
        didCheck = true;
        
        
        
        showDialog(LICENSE_DIALOG);
        
        
    }
    
    @Override
    public void applicationError(ApplicationErrorCode errorCode)
    {
        if (isFinishing())  return;

        licensed = false;
        checkingLicense = false;
        didCheck = true;

        showDialog(LICENSE_DIALOG);

    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        requestWindowFeature(Window.FEATURE_PROGRESS);
    }
    
    protected Dialog onCreateDialog(int id) {
        switch ( id ) 
        {
            case LICENSE_DIALOG: 
                progressDialog.dismiss();
                return new AlertDialog.Builder(this)
                    .setTitle(R.string.unlicensed_dialog_title)
                    .setMessage(errorCode != null ? String.format(getString(R.string.application_error), errorCode) : getString(R.string.unlicensed_dialog_body))
                    .setPositiveButton(R.string.buy_button, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                                    "http://market.android.com/details?id=" + getPackageName()));
                            startActivity(marketIntent);
                            finish();
                        }
                    })
                    .setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
     
                    .setCancelable(false)
                    .setOnKeyListener(new DialogInterface.OnKeyListener(){
                        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                            finish();
                            return true;
                        }
                    })
                    .create();
        }
        
        return null;
 
    }
 
    protected void checkAccess()
    {
        if ( shouldCheckLicense() )
        {
            mHandler = new Handler();

            String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

            mChecker = new LicenseChecker(
                this, new ServerManagedPolicy(this,
                    new AESObfuscator(getSalt(), getPackageName(), deviceId)),
                    getPublicKey());
            
            //check license here
            checkLicense();
        }
        else 
        {
            doProcess();
        }
    }
    
    private void checkLicense() 
    {
        setProgressBarIndeterminateVisibility(true);
        progressDialog = ProgressDialog.show(this, "checking license", "please wait");
        mChecker.checkAccess(this);
    }
    
    protected boolean shouldCheckLicense()
    {
        return false;
    }
    
    protected abstract void process();
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mChecker != null) {
            Log.i("LIcense", "destroy checker");
            mChecker.onDestroy();
        }
    }
}
